<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入申请ID"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="searchClubById">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
         <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          >批量删除</el-button
        >
      </div>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%; height: 520px"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="id" label="申请ID" width="80" sortable />
      <el-table-column prop="userId" label="申请用户ID" width="80" sortable />
      <el-table-column prop="clubName" label="社团名称" width="100" />
      <el-table-column prop="clubIntroduction" label="社团简介" width="150" />
      <el-table-column
        prop="type"
        label="申请类型"
        width="120"
        :filters="typeFilters"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.type === 5" type="success">成立社团</el-tag>
          <el-tag v-else-if="row.type === 6" type="danger">注销社团</el-tag>
          <el-tag v-else-if="row.type === 7" type="info">修改社团信息</el-tag>
          <el-tag v-else type="warning">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="result"
        label="审核结果"
        width="120"
        :filters="resultFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.result === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="row.result === 1" type="success">通过</el-tag>
          <el-tag v-else-if="row.result === 2" type="danger">拒绝</el-tag>
          <el-tag v-else type="info">未知结果</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="120"
        sortable
      />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="120"
        sortable
      />
      <el-table-column
        prop=" isDelete"
        label="是否删除"
        width="100"
        :filters="deleteFilters"
         :filter-method="filterDelete"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.isDelete === 0" type="success">正常</el-tag>
          <el-tag v-else-if="row.isDelete === 1" type="danger">已删除</el-tag>
          <el-tag v-else type="warning">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="190">
        <template #default="{ row }">
          <el-button size="small" @click="handleView(row)">查看</el-button>
          <el-button
            size="small"
            @click="openReasonDialog(row, 'accept')"
            type="success"
            >同意</el-button
          >
          <el-button size="small" @click="openReasonDialog(row, 'reject')" type="danger"
            >拒绝</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count"> 共查询到 {{ total }} 条记录 </span>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        :page-sizes="[4, 10, 20, 50]"
        @current-change="loadTableData"
        @size-change="loadTableData"
      />
    </div>
    <el-dialog title="社团申请详情" v-model="dialogVisible" width="700px">
      <el-card shadow="hover" class="detail-card">
        <el-descriptions
          :column="1"
          border
          size="large"
          label-class-name="detail-label"
          content-class-name="detail-content"
        >
          <el-descriptions-item label="申请ID">{{
            form.id
          }}</el-descriptions-item>
          <el-descriptions-item label="申请用户ID">{{
            form.userId
          }}</el-descriptions-item>
          <el-descriptions-item label="社团ID">{{
            form.clubId
          }}</el-descriptions-item>
          <el-descriptions-item label="申请原因">
            <el-tag type="info" style="white-space: pre-wrap">{{
              form.reason
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            <el-tag>{{ form.createTime }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            <el-tag>{{ form.updateTime }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核结果">
            <el-tag :type="getResultTagType(form.result)">{{
              form.result
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请类型">
            <el-tag :type="getTypeTagType(form.type)">{{ form.type }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="社团名称">
            <el-text type="primary">{{ form.clubName }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="社团简介">
            <div class="intro-box">{{ form.clubIntroduction }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="社团标签">
            <el-space wrap>
              <el-tag
                v-for="(tag, index) in form.clubTags.split(',')"
                :key="index"
              >
                {{ tag }}
              </el-tag>
            </el-space>
          </el-descriptions-item>
          <el-descriptions-item label="新社长ID">{{
            form.newManagerId
          }}</el-descriptions-item>
          <el-descriptions-item label="是否删除">
            <el-tag :type="form.isDelete === '0' ? 'success' : 'danger'">
              {{ form.isDelete === "0" ? "正常" : "已删除" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <template #footer>
        <el-button type="primary" @click="dialogVisible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>

    <!-- 审核原因输入弹窗 -->
    <el-dialog
      v-model="reasonDialogVisible"
      :title="reasonDialogType === 'accept' ? '同意申请' : '拒绝申请'"
      width="400px"
      @close="resetReasonDialog"
    >
      <el-form :model="reasonForm" label-width="80px">
        <el-form-item label="原因" required>
          <el-input
            type="textarea"
            v-model="reasonForm.reason"
            :rows="4"
            maxlength="200"
            show-word-limit
            placeholder="请输入原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="reasonDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="reasonDialogLoading"
          @click="submitReasonDialog"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { getClubApplicationListAPI,deleteClubApplicationsAPI } from "@/apis/club";
import * as XLSX from 'xlsx';
import { doReviewAPI } from "@/apis/review"; 
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();

// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    '社团ID': item.id,
    '社团名称': item.clubName,
    '社团简介':item.clubIntroduction,
    '申请原因':item.reason
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};

const total = ref(0); // 总记录数
const currentPage = ref(1); // 当前页码
const pageSize = ref(7); // 每页记录数
const dialogVisible = ref(false); // 控制对话框显示状态
interface ClubApplication {
  id: number;
  userId: number;
  clubName: string;
  clubIntroduction: string;
  type: number;
  result: number;
  createTime: string;
  updateTime: string;
  reason: string;
  clubTags: string;
  newManagerId: number;
  isDelete: number;
  clubId?: number;
}
const tableData = ref<ClubApplication[]>([]); // 表格数据

// 审核原因弹窗相关
const reasonDialogVisible = ref(false);
const reasonDialogType = ref<'accept' | 'reject'>('accept');
const reasonDialogRow = ref<ClubApplication | null>(null);
const reasonDialogLoading = ref(false);
const reasonForm = ref({
  reason: "",
});

// 打开原因输入弹窗
const openReasonDialog = (row: ClubApplication, type: 'accept' | 'reject') => {
  reasonDialogType.value = type;
  reasonDialogRow.value = row;
  reasonForm.value.reason = "";
  reasonDialogVisible.value = true;
};

// 提交原因弹窗
const submitReasonDialog = async () => {
  if (!reasonForm.value.reason.trim()) {
    ElMessage.warning("请输入原因");
    return;
  }
  reasonDialogLoading.value = true;
  const row = reasonDialogRow.value;
  try {
    if (!row) {
      ElMessage.error("未找到申请数据");
      return;
    }
    // 新增：从 userStore 获取当前用户id
    const reviewerId = userStore.id;
if (!reviewerId) {
  ElMessage.error("无法获取当前用户信息，请重新登录");
  return;
}
    // 使用 doReviewAPI 统一处理同意和拒绝，userid 用当前登录用户id
    const resultValue = reasonDialogType.value === "accept" ? 1 : 2;
    const response = await doReviewAPI(
      reviewerId,
      row.type,
      row.id,
      reasonForm.value.reason,
      resultValue
    );
    if (response.code === 0) {
      ElMessage.success(resultValue === 1 ? "审核通过" : "已拒绝");
      const targetRow = tableData.value.find((item) => item.id === row.id);
      if (targetRow) targetRow.result = resultValue;
      loadTableData();
      reasonDialogVisible.value = false;
    } else {
      ElMessage.error(response.message || (resultValue === 1 ? "审核失败" : "拒绝失败"));
    }
  } catch (error) {
    ElMessage.error("操作失败，请稍后重试");
    console.error(error);
  } finally {
    reasonDialogLoading.value = false;
  }
};

const resetReasonDialog = () => {
  reasonDialogRow.value = null;
  reasonForm.value.reason = "";
  reasonDialogLoading.value = false;
};

// 筛选器
const typeFilters = [
  { text: "成立社团", value: 5 },
  { text: "注销社团", value: 6 },
  { text: "修改社团信息", value: 7 },
];

const deleteFilters = [
  { text: "正常", value: 0 },
  { text: "已删除", value: 1 },
];

const resultFilters = [
  { text: "待审核", value: 0 },
  { text: "通过", value: 1 },
  { text: "拒绝", value: 2 },
];
const loadTableData = async () => {
  try {
    const response = await getClubApplicationListAPI(
      currentPage.value,
      pageSize.value,
      null
    );
    if (
      response.code === 0 &&
      response.data &&
      Array.isArray(response.data.records)
    ) {
      tableData.value = response.data.records; // 绑定表格数据
      total.value = response.data.total || 0; // 设置总记录数
    } else {
      tableData.value = []; // 如果数据为空，设置为空数组
      total.value = 0; // 设置总记录数为 0
      ElMessage.error("加载数据失败：" + response.message);
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    tableData.value = []; // 如果接口调用失败，设置为空数组
    total.value = 0; // 设置总记录数为 0
    ElMessage.error("加载数据失败，请稍后重试");
  }
};

// 存储选中的行数据
const selectedRows = ref<ClubApplication[]>([]);

// 处理选择变化
const handleSelectionChange = (rows: ClubApplication[]) => {
  selectedRows.value = rows;
};

// 修改handleBatchDelete方法
const handleBatchDelete = async () => {
  try {
    if (selectedRows.value.length === 0) {
      ElMessage.warning("请至少选择一条记录");
      return;
    }

    // 确认对话框
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条申请吗？`,
      "批量删除确认",
      { type: "warning" }
    );

    // 获取选中的ID数组
    const selectedIds = selectedRows.value.map((row) => row.id);

    // 调用删除接口，只传ID数组
    const response = await deleteClubApplicationsAPI(selectedIds);

    if (response.code === 0) {
      ElMessage.success(`成功删除 ${selectedIds.length} 条申请`);
      // 刷新数据
      await loadTableData();
      // 清空选中状态
      selectedRows.value = [];
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error(error.message || "批量删除失败");
    }
  }
};
// 组件挂载时加载数据
onMounted(() => {
  loadTableData();
});

const form = ref({
  id: 0,
  userId: 0,
  clubId: 0,
  reason: "",
  createTime: "",
  updateTime: "",
  result: 0,
  type: 0,
  clubName: "",
  clubIntroduction: null,
  clubTags: null,
  newManagerId: null,
  isDelete: 0,
});
const handleView = (row: ClubApplication) => {
  try {
    console.log("点击查看的行数据:", row); // 打印点击的行数据

    form.value = {
      id: row.id || 0,
      userId: row.userId || 0,
      clubId: row.clubId || 0,
      reason: row.reason || "无申请原因",
      createTime: row.createTime || "-",
      updateTime: row.updateTime || "-",
      result: row.result === 0 ? "待审核" : row.result === 1 ? "通过" : "拒绝",
      type:
        row.type === 5
          ? "成立社团"
          : row.type === 6
          ? "注销社团"
          : "修改社团信息",
      clubName: row.clubName || "无社团名称",
      clubIntroduction: row.clubIntroduction || "无社团简介",
      clubTags: row.clubTags || "无标签",
      newManagerId: row.newManagerId || "无新社长",
      isDelete: row.isDelete === 0 ? "正常" : "已删除",
    };

    console.log("转换后的表单数据:", form.value); // 打印转换后的表单数据
    dialogVisible.value = true; // 打开详情对话框
  } catch (error) {
    console.error("查看详情出错:", error);
    ElMessage.error("查看详情失败");
  }
};
// 搜索方法
const searchQuery = ref(""); // 搜索关键词

// 按ID搜索社团
const searchClubById = async () => {
  if (!searchQuery.value) {
    ElMessage.warning("请输入社团ID");
    return;
  }

  try {
    const response = await getClubApplicationListAPI(
      1, // 搜索时重置到第一页
      pageSize.value,
      Number(searchQuery.value) // 传入具体的ID值
    );

    if (response.code === 0) {
      tableData.value = response.data?.records || [];
      total.value = response.data?.total || 0;

      if (tableData.value.length === 0) {
        ElMessage.warning("未找到匹配的社团");
      }
    }
  } catch (error) {
    ElMessage.error("搜索失败");
    console.error("Search error:", error);
  }
};

// 重置搜索
const resetSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  loadTableData(); // 调用获取全部的方法
};
// 筛选方法
const filterType = (value, row) => row.type === value;
const filterResult = (value, row) => row.result === value;
const filterDelete = (value, row) => {
  return row.isDelete === value;
};
// 根据审核结果返回不同的tag类型
const getResultTagType = (result) => {
  const map = {
    通过: "success",
    拒绝: "danger",
    待审核: "warning",
  };
  return map[result] || "info";
};

// 根据申请类型返回不同的tag类型
const getTypeTagType = (type) => {
  const map = {
    加入社团: "",
    创建社团: "success",
    转让社长: "warning",
  };
  return map[type] || "info";
};
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}
.detail-card {
  margin: -20px;
  border-radius: 0;
  border: none;
}

.detail-label {
  width: 120px;
  font-weight: bold;
  background-color: #f5f7fa;
}

.intro-box {
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
  line-height: 1.6;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
